package com.beifu.manager.controller;

import com.beifu.manager.dao.RoleMapper;
import com.beifu.manager.model.*;
import com.beifu.manager.model.RoleExample.Criteria;
//import com.beifu.manager.service.MenuService;
import com.beifu.manager.service.role.RoleModuleService;
import com.beifu.manager.service.role.RoleService;
//import com.beifu.manager.service.RoleUserService;
import com.beifu.manager.service.role.UserRoleRelationService;
import com.beifu.manager.service.user.UserService;
import com.beifu.manager.service.module.ModuleService;
import com.mds.manager.utils.DateUtils;
import com.mds.manager.utils.ListUtils;
import com.mds.manager.utils.PageUtils;
import com.mds.manager.utils.ResponseHelp;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value="/system", produces="text/html;charset=UTF-8")
public class RoleController {
	
	private Logger Log = Logger.getLogger(this.getClass());
	
	@Autowired
	private RoleService roleService;

//	@Autowired
//	private RoleUserService roleUserService;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RoleModuleService roleModuleService;

	@Autowired
	private ModuleService moduleService;
	
	@RequestMapping("/roleIndex")
	public String goRoleIndex(Model model){
		Log.debug(">>>进入角色管理界面");
		return "/system/role/role_index";
	}
	
	/**
	 * 角色列表分页数据
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getRolePage")
	public String getPageData(Model model,HttpServletRequest request, HttpServletResponse res){
		String page = request.getParameter("pageNumber");
		String query_role = request.getParameter("query_role");
		
		RoleExample example = new RoleExample();
		Criteria criteria = example.createCriteria();

		if (!StringUtils.isEmpty(query_role)) {
			criteria.andRoleNameLike("%"+query_role+"%");
		}

		PageUtils Page = new PageUtils(page);
		Page.setQueryParames(example);
		Page = roleService.getRolePage(Page);
		return ResponseHelp.responseText(Page);
	}

	@RequestMapping("/goRoleAdd")
	public String goRoleAdd(Model model){
		Log.debug(">>>进入新增角色界面");
		return "/system/role/role_add";
	}
	
	/**
	 * 是否存在
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleIsExist")
	public String roleIsExist(Model model,HttpServletRequest request) {

		String role = request.getParameter("role");
		RoleExample example = new RoleExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleEqualTo(role);

		List<Role> list = roleService.selectByExample(example);
		if (ListUtils.isNotNull(list)) {
			return ResponseHelp.responseErrorText("角色已存在，不允许重复添加");
		}
		return ResponseHelp.responseText();
	}


	/**
	 * 修改角色状态
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateRoleStatus")
	public String updateRoleStatus(Model model,HttpServletRequest request) {
		Log.debug(">>>进入修改角色状态方法");
		String id = request.getParameter("id");
		String status = request.getParameter("status");

		Role role = roleService.selectByPrimaryKey(Integer.decode(id));
		role.setRoleStatus(status);
		roleService.updateByPrimaryKey(role);
		return ResponseHelp.responseText();
	}

	/**
	 * 新增角色
	 * @param model
	 * @param request
	 * @param res
	 * @return
	 */
	@ResponseBody

	@RequestMapping("/roleAdd")
	public String roleAdd(Model model,HttpServletRequest request){
		String roleNo = request.getParameter("role");
		String roleName = request.getParameter("role_name");
		String roleDesc = request.getParameter("role_desc");
		String roleType = request.getParameter("role_type");
		String status = request.getParameter("status");

		String permission = request.getParameter("permission");
		String roleUserStr = request.getParameter("roleUser");

		String[] rolePermission = permission.split(",");
		String[] roleUser = roleUserStr.split(",");


		int id = roleMapper.selectMaxId()+1;


		Role role = new Role();
		role.setId(id);
		role.setRole(roleNo);
		role.setRoleName(roleName);
		role.setRoleDesc(roleDesc);
		role.setRoleType(roleType);
		role.setRoleStatus("on".equals(status)?"1":"2");
		role.setCreateTime(DateUtils.getDateTime());

		//绑定的用户
		List<UserRoleRelation> roleUserList = new ArrayList<UserRoleRelation>();

		if (roleUser != null && roleUser.length > 0) {
			for (String user : roleUser) {
				if (org.apache.commons.lang.StringUtils.isNotBlank(user)) {
					UserRoleRelation record = new UserRoleRelation();
					record.setRoleId(id);
					record.setUserId(Integer.valueOf(user));
					roleUserList.add(record);
				}
			}
		}


		//绑定的权限
		List<RoleModule> roleModuleList = new ArrayList<RoleModule>();
		for (String rr : rolePermission) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(rr)) {
				RoleModule rp = new RoleModule();
				rp.setModuleId(Integer.valueOf(rr));
				rp.setRoleId(id);
				roleModuleList.add(rp);
			}
		}

		roleService.insert(role,roleUserList,roleModuleList);
		return ResponseHelp.responseText();
	}

	@RequestMapping("/goRoleUpdate")
	public String goRoleUpdate(Model model,HttpServletRequest request){
		Log.debug(">>>进入角色修改界面");
		String id = request.getParameter("id");
		Role role = roleService.selectByPrimaryKey(Integer.decode(id));
		model.addAttribute("role", role);
		return "/system/role/role_update";
	}


	/**
	 * 角色修改
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleUpdate")
	public String roleUpdate(Model model,HttpServletRequest request){
		String id = request.getParameter("id");
		String roleNo = request.getParameter("role");
		String roleName = request.getParameter("role_name");
		String roleDesc = request.getParameter("role_desc");
		String roleType = request.getParameter("role_type");
		String status = request.getParameter("status");

		String permission = request.getParameter("permission");
		String roleUserStr = request.getParameter("roleUser");

		String[] rolePermission = permission.split(",");
		String[] roleUser = roleUserStr.split(",");

		Role role = new Role();
		role.setId(Integer.decode(id));
		role.setRole(roleNo);
		role.setRoleName(roleName);
		role.setRoleDesc(roleDesc);
		role.setRoleType(roleType);
		role.setRoleStatus("on".equals(status)?"1":"2");
		role.setCreateTime(DateUtils.getDateTime());

		//绑定的用户
		List<UserRoleRelation> roleUserList = new ArrayList<UserRoleRelation>();

		if (roleUser != null && roleUser.length > 0) {
			for (String user : roleUser) {
				if (org.apache.commons.lang.StringUtils.isNotBlank(user)) {
					UserRoleRelation record = new UserRoleRelation();
					record.setRoleId(Integer.decode(id));
					record.setUserId(Integer.valueOf(user));
					roleUserList.add(record);
				}
			}
		}


		//绑定的权限
		List<RoleModule> roleModuleList = new ArrayList<RoleModule>();
		for (String rr : rolePermission) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(rr)) {
				RoleModule rp = new RoleModule();
				rp.setModuleId(Integer.valueOf(rr));
				rp.setRoleId(Integer.decode(id));
				roleModuleList.add(rp);
			}
		}


		roleService.updateRoleUserPermission(role, roleUserList, roleModuleList);
		return ResponseHelp.responseText();
	}


	/**
	 * 删除角色
	 * @param model
	 * @param request
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleDel")
	public String roleDel(Model model,HttpServletRequest request){
		String ids = request.getParameter("ids");
		String[] idsArr = ids.split(",");
		for (String id : idsArr) {
			if ("1".equals(id)) {
				return ResponseHelp.responseErrorText("admin角色不允许被删除");
			}
		}
		roleService.batchDelRole(ids.split(","));
		return ResponseHelp.responseText();
	}

	@RequestMapping("/goRoleBindUser")
	public String goRoleBindUser(Model model,HttpServletRequest request){
		Log.debug(">>>进入角色用户授权添加界面");
		// 角色id
		String id = request.getParameter("id");

		// 获取该角色下的用户列表
		List<UserInfo> inList = new ArrayList<UserInfo>();
		// 获取不再该角色下的用户列表
		List<UserInfo> outList = new ArrayList<UserInfo>();

		List<UserInfo> list = userService.getUserAndOrganize();
		if (ListUtils.isNotNull(list) && !StringUtils.isEmpty(id)){
			for (UserInfo userInfo: list) {
				if (null != userInfo.getRoleId() && userInfo.getRoleId().toString().equals(id)) {
					inList.add(userInfo);
				} else {
					outList.add(userInfo);
				}
			}
		} else {
			outList.addAll(list);
		}

		model.addAttribute("userInList", inList);
		model.addAttribute("userOutList", outList);
		return "/system/role/role_bindUser";
	}

	@RequestMapping("/goRoleBindPermission")
	public String goRoleBindPermission(Model model,HttpServletRequest request){
		Log.debug(">>>进入角色权限绑定界面");
		// 角色id
		String id = request.getParameter("id");

		List<Module> moduleList = moduleService.getModuleList();
		// 获取该角色下的模块列表
		List<Module> inList = new ArrayList<Module>();
		// 获取不再该角色下的模块列表
		List<Module> outList = new ArrayList<Module>();

		if(org.apache.commons.lang.StringUtils.isNotBlank(id)){
			// 查询该角色所拥有的模块列表
			RoleModuleExample roleModuleExample = new RoleModuleExample();
			roleModuleExample.createCriteria().andRoleIdEqualTo(Integer.valueOf(id));
			List<RoleModule> roleModuleList = roleModuleService.getRoleModuleList(roleModuleExample);

			if (ListUtils.isNotNull(roleModuleList)) {
				for (Module module : moduleList) {
					Boolean status = true;
					for (RoleModule record : roleModuleList) {
						if (record.getModuleId() == module.getId()) {
							inList.add(module);
							status = false;
						}
					}
					if (status) {
						outList.add(module);
					}

				}

			} else {
				outList.addAll(moduleList);
			}

		} else {
			outList.addAll(moduleList);
		}

		model.addAttribute("moduleInList", inList);
		model.addAttribute("moduleOutList", outList);
		return "/system/role/role_bindPermission";
	}
	
}
